﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ServiceModel.Activation;
using System.ServiceModel;
using System.IO;
using System.ServiceModel.Web;
using System.Net;
using System.Security;
using COFE.Core.Utils;
using COFE.Core.Profile;
using COFE.Core;
using COFE.Data;
using System.Text.RegularExpressions;

namespace COFE.Web.Services
{
    /// <summary>
    /// Services that enables looking up an entry by using file paths.
    /// </summary>
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
    public class UserServices : IUserServices
    {

        public UserServices()
        {

        }

        private bool decodeCredentialStream(Stream credentialStream, out string userName, out string password)
        {
            string credentialString = null;
            using (StreamReader sr = new StreamReader(credentialStream))
                credentialString = sr.ReadToEnd();

            var variableDic = StringUtils.ParamStringToDic(credentialString);
            if (variableDic.ContainsKey("username") && variableDic.ContainsKey("password"))
            {
                userName = variableDic["username"];
                password = variableDic["password"];
                return true;
            }
            else
            {
                userName = password = "";
                return false;
            }

        }

        public void SignIn(Stream credentialStream)
        {
            ServicesUtils.Execute((cstream) =>
                {
                    string userName, password;
                    IUserProfile2 user = null;

                    if (decodeCredentialStream(credentialStream, out userName, out password))
                    {
                        user = COFEWSShared.UserProfileManager.Login(userName, password);
                    }
                    else
                    {
                        var sig = HttpContext.Current.Request.Cookies["cofews_signature"];
                        if (sig != null)
                            user = COFEWSShared.UserProfileManager.Login(new Guid(sig.Value));
                    }

                    if (user == null)
                        throw new SecurityException();

                    HttpContext.Current.Response.AppendCookie(new HttpCookie("cofews_signature", user.AuthorizationKey.ToString()) { Expires = user.AuthorizationExpireTimeUtc });
                    WebOperationContext.Current.OutgoingResponse.Headers.Add("Authorization", "COFEWS");
                    WebOperationContext.Current.OutgoingResponse.Headers.Add("cofews_version", "1.0");
                    WebOperationContext.Current.OutgoingResponse.Headers.Add("cofews_signature", user.AuthorizationKey.ToString());
                    WebOperationContext.Current.OutgoingResponse.Headers.Add("cofews_expireTime", user.AuthorizationExpireTimeUtc.ToString());
                    //WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.SeeOther;
                    //WebOperationContext.Current.OutgoingResponse.Location = "/users/" + userName;




                }, credentialStream, false);
        }

        public void SignOut()
        {
            ServicesUtils.Execute(() =>
            {
                var sig = HttpContext.Current.Request.Cookies["cofews_signature"];                
                if (sig != null && !String.IsNullOrEmpty(sig.Value))
                    COFEWSShared.UserProfileManager.Logout(new Guid(sig.Value));

                HttpContext.Current.Response.SetCookie(new HttpCookie("cofews_signature", "") { Expires = DateTime.MinValue });

            }, false);
        }
    }
}